package cn.hzu580.bean;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionContext;

import cn.hzu580.dao.BaseDAO;
import cn.hzu580.entity.Login;
import cn.hzu580.entity.User;

/**
 * 存放SessionID与uid映射的池，用于保证一个帐号在新的Session中登录后，旧Session会被注销
 * @author 沫熊工作室 <a href="http://www.darhao.cc">www.darhao.cc</a>
 */
@Component
public class LoginedUserPool {
	
	@Resource(name="DAO")
	private BaseDAO baseDAO;
	
	
	/**
	 * 获取当前登录的用户
	 * @return
	 */
	public User getCurrentUser(){
		return (User) baseDAO.get(User.class, (Serializable) ActionContext.getContext().getSession().get("uid"));
	}
	
	
	
	
	/**
	 * 登录之后调用该方法
	 */
	public void login(){
		//获取SessionID和Uid
		HttpSession session = ServletActionContext.getRequest().getSession();
		String sessionID = session.getId();
		String uid = (String) session.getAttribute("uid");
		User user = (User) baseDAO.get(User.class, uid);
		//遍历表，如果存在同样uid的记录则覆盖sessionID
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("uid", uid);
		List<Login> list = (List<Login>) baseDAO.exeQuery("from Login where user.uid=:uid", map);
		if(list.size() == 1){
			Login login = list.get(0);
			login.setSession_id(sessionID);
			baseDAO.update(login);
			return;
		}
		//不存在同样uid则添加一条记录
		Login login = new Login();
		login.setSession_id(sessionID);
		login.setUser(user);
		baseDAO.insert(login);
	}
	
	
	/**
	 * 登出之后调用该方法
	 */
	public void logout(){
		//获取SessionID和Uid
		HttpSession session = ServletActionContext.getRequest().getSession();
		String sessionID = session.getId();
		//遍历表，找到对应登出的sessionID并删除该记录
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("session_id", sessionID);
		baseDAO.exeUpdate("delete from Login where session_id=:session_id", map);
	}
	
	
	/**
	 * 判断该SessionID是否已经登录
	 * @return
	 */
	public boolean isLogined(){
		String sessionID = ServletActionContext.getRequest().getSession().getId();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("session_id", sessionID);
		List<Login> list = (List<Login>) baseDAO.exeQuery("from Login where session_id=:session_id", map);
		if (list.size() != 0) {
			return true;
		}
		return false;
	}

	

	public BaseDAO getBaseDAO() {
		return baseDAO;
	}


	public void setBaseDAO(BaseDAO baseDAO) {
		this.baseDAO = baseDAO;
	}
	
	
}
